package com.kjc.demo.basic.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kjc.demo.basic.util.FtpUtils;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping(value = "/ftp")
@Slf4j
public class FtpTestController {
	
	@Autowired
	private FtpUtils ftpUtils;
	
	private final static String FTP_PREFIX_PATH = "/pub/";
	
	@GetMapping("/uploadFile")
	public String setredisvalue(HttpServletRequest request) {
		String key = request.getParameter("key");
		String value = request.getParameter("value");
		generateFile();
		log.info("redis");
		return "success";
	}
	
	private void generateFile() {
		String reqno = "20200528" + "_CCBK_05_"+28;//批次号
    	String fileName = reqno+".DAT";// 文件名称
		String filePath = "F:/code/"; // 文件路径
		log.info("【创建文件-建设银行】文件绝对路径：{}", filePath + fileName);
		//为所有符合条件的记录赋值批次号
		Object[] head = { "1", "10" };
		List<Object> headList = Arrays.asList(head);
		// 数据
		log.info("【写入文件-建设银行】开始往文件写入数据，总记录数{},总金额{}", 1, 10);
		List<List<Object>> dataList = new ArrayList<List<Object>>();
		List<Object> rowList = null;
		for(int i=0 ; i < 5 ; i++){
			rowList = new ArrayList<Object>();
			rowList.add("123");
			rowList.add("123");
			rowList.add("123");
			rowList.add("123");
			rowList.add("123");
			rowList.add("123");
			rowList.add("123");
			rowList.add("123");
			dataList.add(rowList);
		}
		File datFile = null;
		BufferedWriter csvWtriter = null;
		try {
			datFile = new File(filePath + fileName);
			File parent = datFile.getParentFile();
			if (parent != null && !parent.exists()) {
				parent.mkdirs();
			}
			datFile.createNewFile();
			// UTF-8使正确读取分隔符","
			csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(datFile), "UTF-8"), 1024);
			// 写入文件头部
			writeRow(headList, csvWtriter);
			// 写入文件内容
			for (List<Object> row : dataList) {
				writeRow(row, csvWtriter);
			}
			csvWtriter.flush();
			log.info("【写入文件-建设银行】开始往文件写入数据完成!!!!");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("【写入文件-建设银行】建设银行批量代扣往文件里写数据失败！！！");
		} finally {
			try {
				csvWtriter.close();
			} catch (IOException e) {
				e.printStackTrace();
				log.error("【上传文件-建设银行】文件上传FTP结果：{}", e);
			}
		}
    	//创建dat文件，并写入文件end,上传文件
		String result = uploadFile(filePath,fileName);
	}
	
	/**
	 * originfilename: 待上传文件的绝对路径
	 * */
	private String uploadFile(String filepath , String filename){
//		FtpUtils ftpUtils = new FtpUtils();
		//初始化ftp客户端
		this.ftpUtils.initFtpClient();
		boolean isSuccess = ftpUtils.uploadFile(FTP_PREFIX_PATH, filename, filepath+filename);
		String result = "fail";
		if(isSuccess){
			result = "success";
		}
		return result;
	}
	
	/**
	 * 写一行数据
	 * 
	 * @param row
	 *            数据列表
	 * @param csvWriter
	 * @throws IOException
	 */
	private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException {
		String separator = "|";
		StringBuffer sb = new StringBuffer();
		for (Object data : row) {
//			String rowStr = sb.append("\"").append(data).append("\""+separator).toString();
			sb.append(data).append(separator);
		}
		csvWriter.write(sb.substring(0, sb.length()-1).toString());
		csvWriter.newLine();
	}
	
	
}
